//
//  YJNetworkMngTool.swift
//  yuejian
//
//  Created by gyy on 2017/9/26.
//  Copyright © 2017年 gyy. All rights reserved.
//

import UIKit

 //private var single = YJNetworkMngTool()
var SessionID:String!
var dict:NSDictionary! = nil

class YJNetworkMngTool: NSObject {
      static var SessionID:String!
      private lazy var popup = Popup()
     static var  sharedNetWorkMngTool   = YJNetworkMngTool()
    private override init() {}
    private var sessionManager = AFHTTPSessionManager()
   // let single = YJNetworkMngTool()
//    class func sharedNetWorkMngTool()-> YJNetworkMngTool {
//       return single
//    }

    
    func YJNetwork_Logon(_ parameters: NSDictionary, view: UIView, block: @escaping (_ flag: NSString) -> Void) {

    
    
        let afManager = AFHTTPRequestOperationManager()
        
        afManager.get("http://172.24.10.175/workout/api.php/login", parameters: parameters, success: {(operation:AFHTTPRequestOperation?,responseObject:Any?) in
            MBProgressHUD.hide(for:view,animated:true)
            
            //直接解析返回值
            print(responseObject)
            //                    let userid = (responseObject as! NSDictionary).object(forKey: "userid") as! NSString
            //                    if userid != "0" {
            //                        print("登录成功")
            //                    } else {
            //                        print("登录失败")
            //                    }
            
            
            //let logonReturnModel = ROLogonReturnModel.logonReturnModelWithDict(responseObject as! NSDictionary)
            //登录成功够保存用户名和密码
            
            var test = responseObject as!NSDictionary
            if test.count > 2
            {
                print("success")
                let success = (responseObject as! NSDictionary).object(forKey: "id") as! NSString
                if success != "0"{
                    
                    let SessionID = (responseObject as! NSDictionary).object(forKey: "sessionid") as! NSString
                    print(SessionID)
                    print("登录成功")
                    block("1")
                }
                
            }
            else
            {
                print("fail")
                let success = (responseObject as! NSDictionary).object(forKey: "error") as! NSString
                if success == "用户名或密码不正确"{
                    MBProgressHUD.showDelayHUDToView(view, message: "用户名或密码不正确")
                    print("用户名或密码不正确")
                    block("0")
                }
                
                
            }
            
        }, failure:  { (Operation:AFHTTPRequestOperation?, error:Error?) in
            
            MBProgressHUD.hide(for:view,animated:true)
            MBProgressHUD.showDelayHUDToView(view, message: "网络原因加载失败")
            block("0")
            
        })
    }

    
    func YJNetwork_Register(_ parameters: NSDictionary, view: UIView, block: @escaping (_ flag: NSString) -> Void) {
    print(parameters)
        MBProgressHUD.showAdded(to: view, animated: true)
        let afManager = AFHTTPRequestOperationManager()
        afManager.get("http://172.24.10.175/workout/api.php/reg", parameters:parameters , success: {(oeration: AFHTTPRequestOperation?, responseObject:Any?) in
            
            print(responseObject)
            MBProgressHUD.hide(for: view, animated: true)
            //将返回的字典转换为模型对象
            var test = responseObject as!NSDictionary
            if test.count > 2
            {
                print("success")
                let success = (responseObject as! NSDictionary).object(forKey: "id") as! NSString
                if success != "0"{
                    
                    //                    let SessionID = (responseObject as! NSDictionary).object(forKey: "sessionid") as! NSString
                    //                    print(SessionID)
                    print("注册成功")
                    block("1")
                }
                
            }
            else
            {
                print("fail")
                let success = (responseObject as! NSDictionary).object(forKey: "error") as! NSString
                if success == "手机号已被使用"{
                    MBProgressHUD.showDelayHUDToView(view, message: "手机号已被使用")
                    print("手机号已被使用")
                    block("0")
                }
                
                
            }
        }) { (operation: AFHTTPRequestOperation?, error:Error?) in
            //失败结束转
            MBProgressHUD.hide(for: view, animated: true)
            MBProgressHUD.showDelayHUDToView(view, message: "网络原因注册失败！")
            block("0")
        }
    }
    func YJNetwork_focus_Join(parameter:NSDictionary,block:@escaping ()->Void){
        post(urlStr: "http://172.24.10.175/workout/api.php/focus", parameter: parameter, block: nil)
        block()
    }
    func YJNetwork_delete(parameter:NSDictionary,block:@escaping ()->Void){
        post(urlStr: "http://172.24.10.175/workout/api.php/delete/mod/fans", parameter: parameter, block: nil)
        block()
    }
    
    func isExits(parameter:NSDictionary,block:@escaping (Bool)->Void){
        post(urlStr: "http://172.24.10.175/workout/api.php/isExits/mod/fans", parameter: parameter) { (json) in
            if let dict = json as? NSDictionary{
                DispatchQueue.main.async {
                    self.popup.appear(title: dict.value(forKey: "error") as! String, action: nil)
                }
            }else{
                let str = json as! String
                if str == "0"{
                    block(true)
                }else{
                    block(false)
                }
            }
        }
        
    }
    private func post(urlStr:String,parameter:NSDictionary,block:((_ data:Any?)->Void)?){
        let paraArray = NSMutableArray()
        for (key,value) in parameter{
            let str = "\(key)=\(value)"
            paraArray.add(str)
        }
        let body = paraArray.componentsJoined(by: "&")
        var request = URLRequest(url: URL(string: urlStr)!)
        request.httpMethod = "post"
        request.httpBody = body.data(using: String.Encoding.utf8)
        
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            if data != nil{
                if let json = try? JSONSerialization.jsonObject(with: data!, options: .mutableContainers){
                    block!(json)
                }
                else{
                    if let str = String(data: data!, encoding: String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.GB_18030_2000.rawValue)))){
                        print(str)
                        block?(str)
                    }else if let str = String(data: data!, encoding: .utf8){
                        print(str)
                        block?(str)
                    }
                }
            }else{
                print("返回为空")
                print(error.debugDescription)
            }
        }
        task.resume()
    }
}

